<template>
    <NDrawer v-model:show="visible" width="800px" placement="right" @after-leave="reset">
        <NDrawerContent :title="id ? '编辑广告' : '创建广告'">
            <NForm ref="formRef" :model="form" :rules="rules">
                <NFormItem label="广告类型" path="type">
                    <NSelect v-model:value="form.type" :options="AdTypeOptions"></NSelect>
                </NFormItem>
                <NFormItem label="广告名称" path="title">
                    <NInput v-model:value="form.title"></NInput>
                </NFormItem>
                <NFormItem label="广告图片" path="img">
                    <Upload
                        @updateList="fileList => fileListUpdate(fileList, '')"
                        :default-file-list="fileList"
                        :max="1"
                        accept=".png, .jpg, .jpeg"
                    />
                </NFormItem>
                <NFormItem label="广告名称（繁体）" path="titleZh">
                    <NInput v-model:value="form.titleZh"></NInput>
                </NFormItem>
                <NFormItem label="广告图片（繁体）" path="img">
                    <Upload
                        @updateList="fileList => fileListUpdate(fileList, 'zh')"
                        :default-file-list="fileListZh"
                        :max="1"
                        accept=".png, .jpg, .jpeg"
                    />
                </NFormItem>
                <NFormItem label="广告名称（英文）" path="titleEn">
                    <NInput v-model:value="form.titleEn"></NInput>
                </NFormItem>
                <NFormItem label="广告图片（英文）" path="img">
                    <Upload
                        @updateList="fileList => fileListUpdate(fileList, 'en')"
                        :default-file-list="fileListEn"
                        :max="1"
                        accept=".png, .jpg, .jpeg"
                    />
                </NFormItem>
                <NFormItem label="上线" path="status">
                    <NSwitch v-model:value="form.status" size="small" :unchecked-value="2" :checked-value="1" />
                </NFormItem>
            </NForm>
            <template #footer>
                <NButton @click="submit" :loading="submitLoading" type="primary">确定</NButton>
            </template>
        </NDrawerContent>
    </NDrawer>
</template>

<script setup lang="ts">
import { ref, watchEffect } from 'vue'
import { useMessage, type FormRules, type FormInst, type UploadFileInfo } from 'naive-ui'
import { createAd, queryAdDetail, updateAd } from '@/api/content'
import { AdTypeOptions } from '@/constants/content'
import Upload, { type UploadFileResponse } from '@/components/Upload.vue'

defineOptions({
    name: 'AdCreateDrawer'
})

const props = defineProps<{
    id: number | null
}>()
const emits = defineEmits<{
    refresh: []
}>()
const message = useMessage()

const visible = defineModel<boolean>({
    required: true
})

const formRef = ref<FormInst | null>(null)
const initValue: Api.Content.AdCreateParams = {
    type: null,
    title: '',
    titleZh: '',
    titleEn: '',
    img: '',
    imgZh: '',
    imgEn: '',
    status: 1,
    requestIds: ['', '', '']
}
const form = ref<Api.Content.AdCreateParams>({ ...initValue })

function reset() {
    console.log('reset')
    form.value = { ...initValue }
    form.value.requestIds = ['', '', '']
    clearUploadImage()
}

const rules: FormRules = {
    type: {
        required: true,
        type: 'number',
        message: '请选择',
        trigger: 'change'
    },
    title: {
        required: true,
        message: '请输入',
        trigger: 'change'
    },
    titleZh: {
        required: true,
        message: '请输入',
        trigger: 'change'
    },
    titleEn: {
        required: true,
        message: '请输入',
        trigger: 'change'
    },
    img: {
        required: true,
        message: '请上传',
        trigger: 'change'
    },
    imgZh: {
        required: true,
        message: '请上传',
        trigger: 'change'
    },
    imgEn: {
        required: true,
        message: '请上传',
        trigger: 'change'
    }
}

const fileList = ref<UploadFileInfo[]>([])
const fileListZh = ref<UploadFileInfo[]>([])
const fileListEn = ref<UploadFileInfo[]>([])
const detail = ref<Api.Content.Ad | null>(null)
const queryDetail = async () => {
    if (!props.id) return
    const [err, res] = await queryAdDetail(props.id)
    if (!err && res) {
        detail.value = res
        Object.assign(form.value, res)

        fileList.value.push({
            id: 'a',
            url: res.img,
            name: '中文广告图片',
            status: 'finished'
        })

        fileListZh.value.push({
            id: 'a',
            url: res.imgZh,
            name: '繁体广告图片',
            status: 'finished'
        })

        fileListEn.value.push({
            id: 'a',
            url: res.imgEn,
            name: '英文广告图片',
            status: 'finished'
        })
    }
}

function clearUploadImage() {
    fileList.value.splice(0, fileList.value.length)
    fileListZh.value.splice(0, fileListZh.value.length)
    fileListEn.value.splice(0, fileListEn.value.length)
}

watchEffect(() => {
    if (visible.value && props.id) queryDetail()
})

const fileListUpdate = (fileList: UploadFileResponse[], type: string) => {
    console.log(fileList)
    if (fileList.length) {
        const { requestId, imageUrl } = fileList[0].response!
        if (!type) {
            form.value.img = imageUrl
            form.value.requestIds![0] = requestId
        } else if (type === 'zh') {
            form.value.imgZh = imageUrl
            form.value.requestIds![1] = requestId
        } else if (type === 'en') {
            form.value.imgEn = imageUrl
            form.value.requestIds![2] = requestId
        }
    } else {
        if (!type) {
            form.value.img = ''
            form.value.requestIds![0] = ''
        } else if (type === 'zh') {
            form.value.imgZh = ''
            form.value.requestIds![1] = ''
        } else if (type === 'en') {
            form.value.imgEn = ''
            form.value.requestIds![2] = ''
        }
    }
}

const submitLoading = ref(false)
async function submit() {
    formRef.value?.validate(async errors => {
        console.log(errors)
        if (errors) return
        props.id ? edit() : add()
    })
}

async function add() {
    submitLoading.value = true
    const [err, res] = await createAd(form.value)
    submitLoading.value = false
    if (!err) {
        if (res) message.success('操作成功')
        visible.value = false
        emits('refresh')
    }
}

async function edit() {
    submitLoading.value = true
    const { requestIds, ...opts } = form.value
    console.log(requestIds)
    const [err, res] = await updateAd(props.id!, {
        ...opts,
        requestIds: requestIds ? requestIds.filter(item => item) : []
    })
    submitLoading.value = false
    if (!err) {
        if (res) message.success('操作成功')
        visible.value = false
        emits('refresh')
    }
}
</script>
